<?php
/**
 * Options handler
 *
 * Actions:
 * 		Save: updates the configuration
 *		Default: displays forms for updating the configuration
 */
require_once dirname(dirname(__FILE__)) .'/cse-init.php';

// authentication is required!
Cinnamon::registry('session')->applyAuthenticationPolicy(true);

// fetch required objects from Cinnamon registry
$params = Cinnamon::registry('params');
$view = Cinnamon::registry('view');
$config = Cinnamon::registry('config');

// handle the requested action
switch ( $params->action ) {
	case 'save':
		if ( $params->section == 'auth' ) {
			if ( strcmp($params->auth_pass, $params->auth_passconf) != 0 ) {
				header('Location: options.php?updated=false');
				die();		// avoid further execution
			} else {
				$params->auth_pass = ( empty($params->auth_pass) ) ? 
					$config->get('auth.pass') : md5($params->auth_pass);
				unset($params->auth_passconf);		// unset extra variable				
				
				// update session stored password
				Cinnamon::registry('session')->set('auth.pass', $params->auth_pass);	
					
				$params->auth_required = ( $params->auth_required == 'n' ) ? 'n' : 'y';
			}
		}
		
		// update options
		foreach ( $params as $key => $value ) {
			if ( strstr($key, '_') ) {
				$key = str_replace('_', '.', $key);
				$config->set($key, $value);
			}
		}		
		
		header('Location: options.php?updated=true');
		break;
	default:
		$view->setVariable('config', $config);

		// assign messages
		if ( isset($params->updated) ) {
			if ( strcmp($params->updated, 'true') == 0 ) {
				$view->addMessage(View::NOTICE, 'Options have been updated successfully.');
			} else if ( strcmp($params->updated, 'false') == 0 ) {
				$view->addMessage(View::ERROR, 'Options have not been updated! Please try again.');
			}
		}

		// rendering
		$view->renderHeader();
		$view->render('options-authentication.php');
		$view->render('options-date.php');
		$view->renderFooter();	
		break;
}
?>